package com.controller;

/**
 * Created by wlc on 2018/4/14.
 */

import com.dao.BoneTumorDao;
import com.entity.UserMetadata;
import com.service.BoneTumorOperator;
import com.service.UserOperator;
import com.util.CookieUtil;
import com.util.FileUtil;
import com.util.LocalInformation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;

import static com.util.PermissionUtil.isFOLLOWUPWrite;
import static com.util.PermissionUtil.isQMRead;

/**
 * 映射随访部分
 */
@Controller
@RequestMapping(value = "/follow_up_part",produces = "text/html;charset=UTF-8")
public class FollowPartController {
    //bone_tumor-input
    @RequestMapping(value = "/data_input_bone_tumor",produces = "text/html;charset=UTF-8")
    public ModelAndView data_input_bone_tumor(HttpServletRequest request){
        ModelAndView modelAndView = new ModelAndView();

        String user_cookie_value = CookieUtil.getUserCookie(request).getValue();
        if (user_cookie_value != null && UserMetadata.OnlineUserId.containsKey(user_cookie_value)) {
            UserMetadata.OnlineUserOperatorTime.replace(user_cookie_value, LocalInformation.getTimeID());
            if (isFOLLOWUPWrite(user_cookie_value.split("wlcniubi")[2])){
                //进入数据导入界面
                modelAndView.addObject("id",LocalInformation.getTimeID());
                modelAndView.setViewName("data-input-follow-boneTumor");
            }else {
                modelAndView.setViewName("Permission-Denied");
            }
        }else {
            modelAndView.setViewName("login");
        }

        return modelAndView;
    }

    @RequestMapping(value = "/data_save_bone_tumor",produces = "text/html;charset=UTF-8")
    public ModelAndView data_save_bone_tumor(HttpServletRequest request,
                                             @RequestParam(value = "part1")String part1,
                                             @RequestParam(value = "part2")String part2,
                                             @RequestParam(value = "part3")String part3,
                                             @RequestParam(value = "part4")String part4,
                                             @RequestParam(value = "part5")String part5,
                                             @RequestParam(value = "X_ray_file")CommonsMultipartFile X_ray_file,
                                             @RequestParam(value = "CT_file")CommonsMultipartFile CT_file,
                                             @RequestParam(value = "MR_file")CommonsMultipartFile MR_file,
                                             @RequestParam(value = "US_file")CommonsMultipartFile US_file,
                                             @RequestParam(value = "ECT_file")CommonsMultipartFile ECT_file,
                                             @RequestParam(value = "PET_CT_file")CommonsMultipartFile PET_CT_file,
                                             @RequestParam(value = "Other_file")CommonsMultipartFile Other_file) throws IOException{
        ModelAndView modelAndView = new ModelAndView();

        String user_cookie_value = CookieUtil.getUserCookie(request).getValue();
        if (user_cookie_value != null && UserMetadata.OnlineUserId.containsKey(user_cookie_value)){
            UserMetadata.OnlineUserOperatorTime.replace(user_cookie_value,LocalInformation.getTimeID());

            //影像学文件导入
            ArrayList<CommonsMultipartFile> files = new ArrayList<CommonsMultipartFile>(){
                {
                    add(X_ray_file);
                    add(CT_file);
                    add(MR_file);
                    add(US_file);
                    add(ECT_file);
                    add(PET_CT_file);
                    add(Other_file);
                }
            };
            int time[] = LocalInformation.getNowDate(new Date());
            String file_path = request.getSession().getServletContext().getRealPath("/") + "/file_data/follow_part/BoneTumor/" + time[0] + "_" + time[1] + "_" + time[2] + "/" + part1.split("wlcniubi")[0]+"_";
            String file_names[] = new String[7];

            for(int i = 0; i < 7; i++) {
                if(!files.get(i).getOriginalFilename().equals("")) {
                    file_names[i] = files.get(i).getOriginalFilename();
                    if (FileUtil.createFile(file_path + files.get(i).getOriginalFilename())){
                        File file = new File(file_path + files.get(i).getOriginalFilename());
                        files.get(i).transferTo(file);
                    }
                }else file_names[i] = "null";
            }

            BoneTumorOperator.saveBoneTumorForm(part1,part2,part3,part4,part5, file_names);
            modelAndView.setViewName("SystemHome");
        }else {
            modelAndView.setViewName("login");
        }
        return modelAndView;
    }

    /**
     * 模板下载
     * @param request
     * @param response
     */
    @RequestMapping(value = "/template_download", produces = "text/html;charset=UTF-8")
    public void template_download(HttpServletRequest request, HttpServletResponse response) {

        String rootPath = request.getServletContext().getRealPath("/") + "/WEB-INF/template/";
        String fileName = "boneTumor.xlsx";
        FileUtil.file_download(rootPath, fileName, response);

    }

    @RequestMapping("/upload_file")
    public void save_excel_bone_tumor(@RequestParam(value = "excel_files[]", required = false) CommonsMultipartFile[] files, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String user_cookie_value = CookieUtil.getUserCookie(request).getValue();
        String userId = user_cookie_value.split("wlcniubi")[0];

        int files_size = files.length;      //判断是否上传
        String error_file = "";
        int flag = 0;  // flag = 0 : 上传正确 || flag = 1: 后缀错误  ||flag = 2: 格式错误

        String[] path_list = new String[files_size];
        String[] timeId_list = new String[files_size];

        for(int i = 0; i < files_size; i++) {
            timeId_list[i] = LocalInformation.getTimeID_bias(i);
            path_list[i] =  request.getSession().getServletContext().getRealPath("/")+"/temp_data/"+userId+"/"+timeId_list[i]+'_';
        }

        for(MultipartFile file :files) {
            String file_name = file.getOriginalFilename();
            if(!file_name.endsWith("xlsx")) {
                System.out.println(file_name);
                flag = 1;
                break;
            }
            //上传存储
            FileUtil.data_upload(path_list[files_size - 1], file_name, file);
            //解析excel
            if(!BoneTumorOperator.Analysis_bone_tumor(timeId_list[files_size - 1], path_list[files_size - 1], file_name)) {
                error_file = file_name;
                flag = 2;
                break;
            }
            files_size--;
        }
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out= null;
        out = response.getWriter();
        if(files_size == 0 && flag == 0) {
            out.print("success");
        } else if(flag == 1) {
            out.print("error : suffix error");
        } else  if(flag == 2) {
            out.print("error" + " : " + error_file);
        }
        out.flush();
        out.close();
    }

    /**
     * 进入随访数据查找页面
     * @param request
     * @return
     */
    @RequestMapping("data_search_follow_up")
    public ModelAndView data_search_follow_up(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();

        String user_cookie_value = CookieUtil.getUserCookie(request).getValue();
        if (user_cookie_value != null && UserMetadata.OnlineUserId.containsKey(user_cookie_value)){
            UserMetadata.OnlineUserOperatorTime.replace(user_cookie_value,LocalInformation.getTimeID());
            if (isQMRead(user_cookie_value.split("wlcniubi")[2])){
                //进入数据查找界面
                modelAndView.setViewName("data-search-follow-boneTumor");
            }else {
                modelAndView.setViewName("Permission-Denied");
            }
        }else {
            modelAndView.setViewName("login");
        }
        return modelAndView;
    }

//    /**
//     * 查找随访数据，返回部分
//     * @param response
//     * @throws IOException
//     */
//    @RequestMapping("search_follow_up_start")
//    public void search_follow_up_start(HttpServletResponse response) throws IOException {
//
//        response.setContentType("text/html;charset=utf-8");
//        response.setHeader("Pragma", "No-cache");
//        response.setHeader("Cache-Control", "no-cache");
//        response.setCharacterEncoding("UTF-8");
//        PrintWriter out=response.getWriter();
//
//        out.println(BoneTumorOperator.searchBoneTumor());
//        out.flush();
//        out.close();
//    }

    /**
     * 根据关键词查找随访数据
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/keyword_search_follow",produces = "text/html;charset=UTF-8")
    public void keyword_search_QM(HttpServletRequest request, HttpServletResponse response) throws IOException{
        String user_cookie_value = CookieUtil.getUserCookie(request).getValue();
        UserMetadata.OnlineUserOperatorTime.replace(user_cookie_value,LocalInformation.getTimeID());
        String projectPath = request.getSession().getServletContext().getRealPath("/");

        response.setContentType("text/html;charset=utf-8");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out=response.getWriter();
        out.println(BoneTumorOperator.setSearchResult(user_cookie_value,projectPath,request.getParameter("base"),request.getParameter("keyword")));
        out.flush();
        out.close();
    }

    /**
     * 返回查找后表头，数据
     * @param request
     * @return
     */
    @RequestMapping(value = "/generate_follow_up_table", produces = "text/html;charset=UTF-8")
    public ModelAndView generate_follow_up_table(HttpServletRequest request) throws IOException {

        String select_data_id = request.getParameter("follow_select_result");

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("template-searchTable");

        String user_cookie_value = CookieUtil.getUserCookie(request).getValue();
        UserMetadata.OnlineUserOperatorTime.replace(user_cookie_value,LocalInformation.getTimeID());
        String projectPath = request.getSession().getServletContext().getRealPath("/");                      //Path

        String table_title = StringUtils.join(BoneTumorDao.getHeaderName(),"wlcniubi");
        String table_data = UserOperator.getSearchResult(user_cookie_value,projectPath,select_data_id);
//        table_data = table_data.replaceAll("\"|'|\r\n|\r|\n|\\s*", "");

        modelAndView.addObject("table_data", table_data);
        modelAndView.addObject("table_title", table_title);
        modelAndView.addObject("data_type", "FollowUp");
        return modelAndView;
    }

}
